import Axios, { AxiosRequestConfig } from "axios";
import modal from '@/globalComponents/Modal/index'

export type RequestConfig = AxiosRequestConfig & {
  showLoading?: boolean;
}

type ResponseBody = Record<string, any>
export type RequestMethodFunction = (url: string, data?: any, config?: RequestConfig) => Promise<ResponseBody>
export interface RequestFactory {
  (config: RequestConfig): Promise<Record<string, any>>;
  get: RequestMethodFunction;
  post: RequestMethodFunction;
  put: RequestMethodFunction;
  delete: RequestMethodFunction;
  patch: RequestMethodFunction;
  options: RequestMethodFunction;
  head: RequestMethodFunction;
}

Axios.defaults.baseURL = "http://localhost:9527/api"
Axios.defaults.timeout = 6000

const request: RequestFactory = function (config) {
  return new Promise((resolve, reject) => {
    Axios(config).then(res => {
      if (res.status === 200 && res.data.code === 200) {
        resolve(res.data)
      } else {
        reject({ message: '网路异常' })
        modal.show('网络异常')
      }
    }).catch(err => {
      reject(err)
      modal.show('网络异常')
    })
  })
}

request.get = (url: string, data?: any, config?: RequestConfig) => {
  return request({
    ...config,
    url,
    params: data || {},
    method: "get",
  });
};
request.post = (url: string, data?: any, config?: RequestConfig) => {
  return request({
    ...config,
    url,
    data,
    method: "post",
  });
};
request.put = (url: string, data?: any, config?: RequestConfig) => {
  return request({
    ...config,
    url,
    data,
    method: "put",
  });
};
request.delete = (url: string, data?: any, config?: RequestConfig) => {
  return request({
    ...config,
    url,
    data,
    method: "delete",
  });
};
request.patch = (url: string, data?: any, config?: RequestConfig) => {
  return request({
    ...config,
    url,
    data,
    method: "patch",
  });
};
request.options = (url: string, data?: any, config?: RequestConfig) => {
  return request({
    ...config,
    url,
    data,
    method: "options",
  });
};
request.head = (url: string, data?: any, config?: RequestConfig) => {
  return request({
    ...config,
    url,
    data,
    method: "head",
  });
};

export default request